import uuid

from injector import inject

from internal.exception import NotFoundException
from internal.model import App
from pkg.sqlalchemy import SQLAlchemy


@inject
class AppService:
    db: SQLAlchemy

    def __init__(self, db: SQLAlchemy):
        self.db = db

    def get_app(self, id: uuid.UUID):
        app = self.db.session.query(App).get(id)
        if app is None:
            raise NotFoundException("数据不存在", data={})
        return app

    def addData(self, data: App) -> App:
        with self.db.auto_commit():
            # 1.创建模型的实体类
            app = App(account_id=uuid.uuid4(), name=data["name"], icon=data["icon"], config=data["config"])
            # 2.将实体类添加到session会话中
            self.db.session.add(app)
        return app

    def delData(self, id: uuid.UUID) -> App:
        with self.db.auto_commit():
            data = self.get_app(id)
            self.db.session.delete(data)
        return data

    def updateData(self, id: uuid.UUID, obj: App) -> App:
        with self.db.auto_commit():
            data = self.get_app(id)
            data.name = obj["name"]
            data.icon = obj["icon"]
            data.config = obj["config"]
        return data
